package com.ruoyi.result.longitudinalProjects.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.result.Result;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.result.longitudinalProjects.domain.ResultLongitudinalProjects;
import com.ruoyi.result.longitudinalProjects.domain.dto.ResultLongitudinalProjectsDTO;
import com.ruoyi.result.longitudinalProjects.domain.vo.ResultLongitudinalProjectsVO;
import com.ruoyi.result.longitudinalProjects.service.IResultLongitudinalProjectsService;
import com.ruoyi.system.domain.result_entity.Export.CustomCellWriteHandler;
import com.ruoyi.system.domain.result_entity.Export.ExportField;
import com.ruoyi.system.domain.result_entity.Export.ExportRequest;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 纵向课题Controller
 *
 * @author ruoyi
 * @date 2025-01-22
 */
@Slf4j
@RestController
@RequestMapping("/result/longitudinalProjects")
public class ResultLongitudinalProjectsController extends BaseController
{
    @Autowired
    private IResultLongitudinalProjectsService resultLongitudinalProjectsService;

    /**
     * 查询纵向课题列表
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:list')")
    @GetMapping("/list")
    public TableDataInfo list(ResultLongitudinalProjectsDTO resultLongitudinalProjects)
    {
        TableDataInfo list = resultLongitudinalProjectsService.selectResultLongitudinalProjectsList(resultLongitudinalProjects);
        return list;
    }

    /**
     * 导出纵向课题列表
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:export')")
    @Log(title = "纵向课题", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResultLongitudinalProjects resultLongitudinalProjects)
    {
//        List<ResultLongitudinalProjects> list = resultLongitudinalProjectsService.selectResultLongitudinalProjectsList(resultLongitudinalProjects);
//        ExcelUtil<ResultLongitudinalProjects> util = new ExcelUtil<ResultLongitudinalProjects>(ResultLongitudinalProjects.class);
//        util.exportExcel(response, list, "纵向课题数据");
    }
    @PostMapping("/export/longitudinalProjects")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_Longitudinal.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("Longitudinal")
                .doWrite(transformedData);
    }
    /**
     * 获取纵向课题详细信息
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(resultLongitudinalProjectsService.selectResultLongitudinalProjectsById(id));
    }
    /**
     * 批量获取纵向课题
     */
    @GetMapping("/getLongitudinalProjectsByIds")
    public AjaxResult getLongitudinalProjectsByIds(@RequestParam(value = "ids", required = false) String idsStr) {
        if (StringUtils.isEmpty(idsStr)) {
            log.error("ids 参数为空");
            return AjaxResult.error("ids 参数为空");
        }

        // 将逗号分隔的字符串转换为 Long 数组
        Long[] ids = Arrays.stream(idsStr.split(","))
                .filter(s -> !StringUtils.isEmpty(s))
                .map(Long::parseLong)
                .toArray(Long[]::new);

        List<ResultLongitudinalProjectsVO> resultLongitudinalProjectsList = resultLongitudinalProjectsService.selectResultLongitudinalProjectsByIds(ids);
        if (resultLongitudinalProjectsList == null || resultLongitudinalProjectsList.isEmpty()) {
            return AjaxResult.error("纵向课题不存在");
        }
        return AjaxResult.success(resultLongitudinalProjectsList);
    }
    /**
     * 新增纵向课题
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:add')")
    @Log(title = "纵向课题", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResultLongitudinalProjects resultLongitudinalProjects)
    {
        return toAjax(resultLongitudinalProjectsService.insertResultLongitudinalProjects(resultLongitudinalProjects));
    }

    /**
     * 修改纵向课题
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:edit')")
    @Log(title = "纵向课题", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResultLongitudinalProjects resultLongitudinalProjects)
    {
        return toAjax(resultLongitudinalProjectsService.updateResultLongitudinalProjects(resultLongitudinalProjects));
    }

    /**
     * 删除纵向课题
     */
    @PreAuthorize("@ss.hasPermi('result:longitudinalProjects:remove')")
    @Log(title = "纵向课题", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(resultLongitudinalProjectsService.deleteResultLongitudinalProjectsByIds(ids));
    }

    @GetMapping("/getProjectNameById/{id}")
    @ApiOperation("根据id查询课题名")
    public AjaxResult getProjectNameById(@PathVariable Long id) {
        ResultLongitudinalProjects longitudinal = resultLongitudinalProjectsService.getLongitudinalById(id);

        // 添加空值检查
        if (longitudinal == null) {
            return AjaxResult.error("未找到ID为" + id + "的纵向课题");
        }

        return AjaxResult.success(longitudinal.getProjectName());
    }

}
